<?php

declare(strict_types=1);

namespace app\service\system;

use app\model\system\UserModel;
use owns\enum\CacheMap;
use owns\enum\AppEnum;
use owns\facade\JwtAuth;
use think\facade\Cache;

/**
 * 管理员登录
 */
class LoginService
{
    /**
     * 获取登录用户
     * @param array $param
     */
    public function userLogin(array $param): object
    {
        $user = UserModel::where('username', $param['username'])->find();
        if (!$user) {
            tips('无账户信息');
        }
        if ($user->status == 0) {
            tips('账户已被禁用');
        }
        if (md5($param['password']) !== $user->password) {
            tips('账户或密码错误');
        }
        return $user;
    }

    /**
     * 生成token
     * @param Object $user
     */
    public function generateToken($user): string
    {
        $token = JwtAuth::sign([
            'uid' => $user->id,
            'username' => $user->username,
            'super' => AppEnum::isSuper($user->role_id),
            'role_id' => $user->role_id,
            'group_id' => $user->group_id,
        ]);
        Cache::store('redis')->hset(CacheMap::OWN_USIGN, CacheMap::userCache($user->id), $token);
        return $token;
    }
    /**
     * 获取登录管理员信息
     * @param object $user
     */
    public function userInfo(object $user)
    {
        $field = UserModel::showField();

        $user = UserModel::field($field)
            ->with(['role'])
            ->find($user->id);

        return $user;
    }
    /**
     * @param object $user
     */
    public function auth(object $user)
    {
        return [
            'root' => AppEnum::isSuper($user->role_id),
            'super' => AppEnum::isRoot($user->id)
        ];
    }
    /**
     * 刷新token
     */
    public function refreshToken(int $uid): string
    {
        $user = UserModel::where('id', $uid)->find();
        return $this->generateToken($user);
    }
    /**
     * 登出
     */
    public function logout(int $uid): void
    {
        Cache::store('redis')->hdel(CacheMap::OWN_USIGN, CacheMap::userCache($uid));
    }
}
